package com.redoor.iot.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.redoor.iot.mapper.RoleMapper;
import com.redoor.iot.mapper.RoleMenuRelaMapper;
import com.redoor.iot.mapper.UserRoleRelaMapper;
import com.redoor.iot.model.Role;
import com.redoor.iot.model.RoleMenuRela;
import com.redoor.iot.service.IRoleService;

@Service("roleService")
public class RoleServiceImpl implements IRoleService {

	@Autowired
	private RoleMapper roleMapper;
	
	@Autowired
	private UserRoleRelaMapper userRoleRelaMapper;
	
	@Autowired
	private RoleMenuRelaMapper roleMenuRelaMapper;
	
	
	
    @Transactional
    @Override
    public int save(Role role) {
        int count = roleMapper.save(role);
        List<Long> menuIds = role.getMenuIds();
        Long roleId = role.getRoleId();
        List<RoleMenuRela> rms = new ArrayList<>();
        if(!CollectionUtils.isEmpty(menuIds)) {
        	for (Long menuId : menuIds) {
                RoleMenuRela rmRela = new RoleMenuRela();
                rmRela.setRoleId(roleId);
                rmRela.setMenuId(menuId);
                rms.add(rmRela);
            }
        }
        
        roleMenuRelaMapper.removeByRoleId(roleId);
        if (rms.size() > 0) {
        	roleMenuRelaMapper.batchSave(rms);
        }
        return count;
    }
    
    @Override
    public List<Role> list() {
    	Map<String,Object> params = new HashMap<String,Object>();
    	params.put("status", 0);   //状态(0:有效;1:无效)
        List<Role> roles = roleMapper.list(params);
        return roles;
    }
    
    @Override
    public List<Role> list(Long userId) {
        List<Long> rolesIds = userRoleRelaMapper.listRoleId(userId);
        List<Role> roles = roleMapper.list(new HashMap<>(16));
        for (Role roleDO : roles) {
            roleDO.setRoleSign("false");
            for (Long roleId : rolesIds) {
                if (Objects.equals(roleDO.getRoleId(), roleId)) {
                    roleDO.setRoleSign("true");
                    break;
                }
            }
        }
        return roles;
    }

}
